import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

// 操作按钮排列方式
enum LxAlertActionsAlignment {
  row,
  column,
}

class LxAlert {
  // 弹框
  static Future<void> show(
    String content, {
    String? title,
    String? subContent,
    TextAlign? contentTextAlign,
    bool showCancel = true,
    String confirmTitle = "确认",
    String cancelTitle = "取消",
    Color titleColor = WhiteColor.white1,
    Color contentColor = WhiteColor.white1,
    Color? subContentColor, // 函数中赋值 WhiteColor.white2
    Color? confirmColor,
    Color?
        confirmColorUnvailable, // 函数中赋值 LxWidgetsLibraryService.to.colorType.color3
    Color cancelColor = WhiteColor.white1,
    LxFontWeightEnum titleFontWeight = LxFontWeightEnum.titleLarge,
    LxFontWeightEnum contentFontWeight = LxFontWeightEnum.bodyLarge,
    LxFontWeightEnum subContenFontWeight = LxFontWeightEnum.bodyMedium,
    LxFontWeightEnum confirmFontWeight = LxFontWeightEnum.titleMedium,
    LxFontWeightEnum cancelFontWeight = LxFontWeightEnum.titleMedium,
    Function(String?)? confirmCallback,
    Function? cancelCallback,
    LxAlertActionsAlignment actionsAlignment = LxAlertActionsAlignment.row,
    String? textFieldValue,
    String? textFieldPlaceholder,
    InputType? inputType,
    int? maxLength,
    bool? isShowSecret,
    bool? isSecret,
    Widget? extendWidget,
  }) {
    subContentColor ??= WhiteColor.white2;
    confirmColor ??= LxWidgetsLibraryService.to.colorType.color6;
    confirmColorUnvailable ??= LxWidgetsLibraryService.to.colorType.color3;
    double leftRightSpace = CONTENT_MARGIN;
    double textMaxWidth = 311.w - 2 * leftRightSpace;
    bool hasTitle = title != null;
    bool isOneLine =
        LxTextUtil.computeWidth(content, contentFontWeight.size, 15.h) <=
            textMaxWidth;
    bool hasSubContent = subContent != null;
    // 确定按钮是否可以点击（当输入框为空则不可点击状态）
    RxBool availableConfirmBtn = true.obs;
    // 输入框
    bool hasInput = textFieldValue != null || textFieldPlaceholder != null;
    TextEditingController? textEditingController = TextEditingController();
    RxDouble inputBottom = 0.0.obs;
    StreamSubscription<bool>? keyboardSubscription;
    if (hasInput) {
      availableConfirmBtn.value = textFieldValue != null;
      keyboardSubscription =
          KeyboardVisibilityController().onChange.listen((event) {
        inputBottom.value = event ? 150.h : 0;
      });
    }
    // 扩展组件
    bool hasExtend = extendWidget != null;
    double lineTop =
        isOneLine && !(hasTitle || hasSubContent || hasInput || hasExtend)
            ? 32.h
            : 24.h;
    return SmartDialog.show(
      clickMaskDismiss: false,
      onDismiss: () {
        keyboardSubscription?.cancel();
      },
      builder: (context) {
        return Obx(
          () => Padding(
            padding: EdgeInsets.only(bottom: inputBottom.value),
            child: ClipRRect(
              borderRadius: const BorderRadius.all(Radius.circular(12)),
              child: Container(
                width: textMaxWidth,
                color: GrayColor.gray2,
                child: IntrinsicHeight(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题
                      Visibility(
                        visible: hasTitle,
                        child: Padding(
                          padding: EdgeInsets.only(top: 24.h),
                          child: Center(
                            child: LxText(
                              title,
                              color: titleColor,
                              fontWeightEnum: titleFontWeight,
                            ),
                          ),
                        ),
                      ),
                      // 文本
                      Visibility(
                        visible: content.isNotEmpty,
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: isOneLine ? 32.h : (hasTitle ? 16.h : 24.h),
                            left: leftRightSpace,
                            right: leftRightSpace,
                          ),
                          child: Center(
                            child: LxText(
                              content,
                              color: contentColor,
                              fontWeightEnum: contentFontWeight,
                              textAlign: contentTextAlign,
                            ),
                          ),
                        ),
                      ),
                      // 副文本
                      Visibility(
                        visible: hasSubContent,
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: 8.h,
                            left: leftRightSpace,
                            right: leftRightSpace,
                          ),
                          child: LxText(
                            subContent,
                            color: subContentColor!,
                            fontWeightEnum: subContenFontWeight,
                          ),
                        ),
                      ),
                      // 输入框
                      Visibility(
                        visible: hasInput,
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: 16.h,
                            left: leftRightSpace,
                            right: leftRightSpace,
                          ),
                          child: ClipRRect(
                            borderRadius:
                                const BorderRadius.all(Radius.circular(4)),
                            child: _textField(
                              textEditingController,
                              textFieldValue,
                              textFieldPlaceholder,
                              (value) {
                                availableConfirmBtn.value = value.isNotEmpty;
                              },
                              isShowSecret,
                              isSecret,
                              inputType,
                              maxLength,
                            ),
                          ),
                        ),
                      ),
                      // 扩展
                      Visibility(
                        visible: hasExtend,
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: 16.h,
                            left: leftRightSpace,
                            right: leftRightSpace,
                          ),
                          child: extendWidget,
                        ),
                      ),
                      // 按钮
                      ConfirmWithCancelButton.actionsLayout(
                        context,
                        availableConfirmBtn,
                        lineTop: lineTop,
                        showCancel: showCancel,
                        confirmTitle: confirmTitle,
                        cancelTitle: cancelTitle,
                        confirmColor: confirmColor,
                        confirmColorUnvailable: confirmColorUnvailable,
                        cancelColor: cancelColor,
                        confirmFontWeight: confirmFontWeight,
                        cancelFontWeight: cancelFontWeight,
                        confirmCallback: () {
                          SmartDialog.dismiss();
                          if (confirmCallback != null) {
                            confirmCallback(textEditingController.text);
                          }
                        },
                        cancelCallback: () {
                          SmartDialog.dismiss();
                          if (cancelCallback != null) {
                            cancelCallback();
                          }
                        },
                        actionsAlignment: actionsAlignment,
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  static void dismiss() {
    SmartDialog.dismiss();
  }

  // 输入框
  static _textField(
    TextEditingController inputController,
    String? textFieldValue,
    String? placeholder,
    Function(String)? onChangedValue,
    bool? isShowSecret,
    bool? isSecret,
    InputType? inputType,
    int? maxLength,
  ) {
    return LxTextField(
      value: textFieldValue,
      placeholder: placeholder,
      textFieldType: inputType ?? InputType.text,
      controller: inputController,
      backgroundColor: GrayColor.gray3,
      showClear: true,
      isShowSecret: isShowSecret,
      maxLength: maxLength,
      isSecret: isSecret,
      onChangedValue: (p0) {
        if (onChangedValue != null) {
          onChangedValue(p0);
        }
      },
    );
  }
}
